<template>
  <div class="word-preview-container">
    <div class="preview-header">
      <h3>{{ title }}</h3>
      <div class="action-buttons">
        <el-button type="primary" size="small" @click="toggleEditMode" v-if="fileUrl">
          <i :class="isEditing ? 'el-icon-view' : 'el-icon-edit'"></i>
          {{ isEditing ? '预览' : '编辑' }}
        </el-button>
        <el-button type="success" size="small" @click="saveDocument" v-if="isEditing">
          <i class="el-icon-check"></i> 保存
        </el-button>
        <el-button type="primary" size="small" @click="downloadFile" v-if="fileUrl && !isEditing">
          <i class="el-icon-download"></i> 下载
        </el-button>
      </div>
    </div>
    <div class="preview-content" v-loading="loading">
      <div v-if="!fileUrl" class="empty-state">
        <i class="el-icon-document"></i>
        <p>暂无文件</p>
      </div>
      <div v-else-if="isEditing" class="edit-container">
        <el-input
          type="textarea"
          v-model="documentContent"
          :rows="20"
          placeholder="请输入文档内容"
        ></el-input>
      </div>
      <div v-else ref="previewContainer" class="preview-frame"></div>
    </div>
  </div>
</template>

<script>
import * as docx from 'docx-preview'
import { Document, Packer, Paragraph, TextRun } from 'docx'

export default {
  name: 'WordPreview',
  props: {
    fileUrl: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: '文档预览'
    }
  },
  data() {
    return {
      loading: false,
      previewUrl: '',
      isEditing: false,
      documentContent: '',
      originalContent: '',
      currentDoc: null
    }
  },
  watch: {
    fileUrl: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.loadPreview()
        }
      }
    }
  },
  methods: {
    async loadPreview() {
      this.loading = true
      try {
        if (!docx || !docx.renderAsync) {
          throw new Error('docx-preview 库加载失败')
        }

        // 获取文档内容
        const response = await fetch(this.fileUrl)
        const arrayBuffer = await response.arrayBuffer()
        
        // 保存原始内容
        this.originalContent = await this.arrayBufferToText(arrayBuffer)
        this.documentContent = this.originalContent
        
        // 渲染文档
        await docx.renderAsync(
          arrayBuffer,
          this.$refs.previewContainer,
          null,
          {
            className: 'docx-preview',
            inWrapper: true,
            ignoreWidth: false,
            ignoreHeight: false,
            ignoreFonts: false,
            breakPages: true,
            debug: false,
            experimental: false,
            className: 'docx'
          }
        )
        
        this.$message.success('文档加载成功')
      } catch (error) {
        console.error('加载文档失败:', error)
        this.$message.error(`加载文档失败: ${error.message}`)
      } finally {
        this.loading = false
      }
    },
    async arrayBufferToText(arrayBuffer) {
      try {
        // 使用 docx-preview 的渲染结果获取文本
        const container = document.createElement('div')
        await docx.renderAsync(arrayBuffer, container)
        return container.textContent
      } catch (error) {
        console.error('转换文档失败:', error)
        return '文档内容加载失败'
      }
    },
    toggleEditMode() {
      this.isEditing = !this.isEditing
      if (!this.isEditing) {
        this.loadPreview()
      }
    },
    async saveDocument() {
      try {
        // 创建新的文档
        const doc = new Document({
          sections: [{
            properties: {},
            children: this.documentContent.split('\n').map(text => 
              new Paragraph({
                children: [new TextRun(text)]
              })
            )
          }]
        })

        // 生成文档
        const blob = await Packer.toBlob(doc)
        const url = URL.createObjectURL(blob)
        
        // 触发保存事件
        this.$emit('save', {
          content: this.documentContent,
          blob: blob,
          url: url
        })
        
        this.$message.success('文档保存成功')
        this.isEditing = false
        
        // 更新预览
        this.fileUrl = url
        this.loadPreview()
      } catch (error) {
        console.error('保存文档失败:', error)
        this.$message.error(`保存文档失败: ${error.message}`)
      }
    },
    downloadFile() {
      if (this.fileUrl) {
        window.open(this.fileUrl, '_blank')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.word-preview-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .preview-header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #303133;
    }
  }

  .preview-content {
    height: 700px;
    position: relative;
    overflow: auto;

    .empty-state {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #909399;

      i {
        font-size: 48px;
        margin-bottom: 16px;
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }

    .edit-container {
      padding: 20px;
      height: 100%;
      box-sizing: border-box;
    }

    .preview-frame {
      width: 100%;
      height: 100%;
      padding: 20px;
      box-sizing: border-box;
    }
  }
}

// 自定义docx-preview样式
.docx-preview {
  .docx-wrapper {
    background: #fff;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }
  
  table {
    border-collapse: collapse;
    width: 100%;
    margin: 10px 0;
  }
  
  table td, table th {
    border: 1px solid #dcdfe6;
    padding: 8px;
  }
  
  p {
    margin: 10px 0;
    line-height: 1.6;
  }
}
</style>
